package me.zk.practice1.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author: zhang kai
 * @Date: 2021/12/20
 * @Description:
 */
public class CasDemo {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);
        //线程t1，负责完成ABA的执行
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "当前stamp：" + atomicStampedReference.getStamp());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(atomicStampedReference.getReference(),atomicStampedReference.getReference() + 1
                    ,atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            atomicStampedReference.compareAndSet(atomicStampedReference.getReference(),100
                    ,atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
        },"t1").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "当前stamp：" + atomicStampedReference.getStamp());
            int stamp = atomicStampedReference.getStamp();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = atomicStampedReference.compareAndSet(atomicStampedReference.getReference(),atomicStampedReference.getReference() + 1
                    ,stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName() + "执行结果：" + result);
        },"t2").start();
//        while (Thread.activeCount() > 2) {
//
//        }
    }
}
